<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 400px;
            height: 40px;
            border: 1px solid rgb(83, 47, 47);
            margin-bottom: 10px;
            line-height: 40px;
        }

        .spn1 {
            display: inline-block;
            width: 0px;
            height: 40px;
            background-color: red;
            text-align: center;
        }
    </style>
</head>

<body>
    <div class="box">
        <span class="spn1">0%</span>

    </div>
    <button>安装</button>

    <script>
        const spn1 = document.querySelector('.spn1')
        const but = document.querySelector('button')


        let num = 0
        let time = null
        // 绑定点击事件
        but.onclick = function () {

            // 给计时器添加一个判断条件,只有为null时才能开启,否则不开启
            if (time == null) {
                // 启动计时器
                time = setInterval(() => {
                    // 每秒加40,然后赋值给宽度
                    num += 17
                    spn1.style.width = num + 'px'
                    // 换算百分比,然后赋值
                    spn1.innerHTML = Math.floor(num / 400 * 100) + '%'
                    console.log(num);
                    // 宽度大于等于400时关闭计时器
                    if (num >= 400) {
                        clearInterval(time)
                    }

                }, 1000)

            }


        }
    </script>
</body>

</html>